package com.angel.utils;

import com.angel.bean.Employee;
import com.angel.service.EmployeeService;
import com.angel.shiro.SystemAdminAuthorizingRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.subject.Subject;

public class  EmployeeUtils {

    private static EmployeeService employeeService = SpringUtil.getBean(EmployeeService.class);

    /**
     * 获取当前登录者对象
     */
    public static SystemAdminAuthorizingRealm.Principal getPrincipal() {
        try {
            Subject subject = SecurityUtils.getSubject();
            SystemAdminAuthorizingRealm.Principal principal = (SystemAdminAuthorizingRealm.Principal) subject.getPrincipal();
            if (principal != null) {
                return principal;
            }
        } catch (UnavailableSecurityManagerException e) {

        } catch (InvalidSessionException e) {

        }
        return null;
    }


    /**
     * 根据ID获取登录的员工
     * @param id 员工id
     * @return 取不到返回null
     */
    public static Employee get(Integer id){
        Employee employee= new Employee();
        employee.setEmId(id);
        return employeeService.findOne(employee);
    }

    /**
     * 获取当前登录的管理员
     * @return 取不到返回 new Employee()
     */
    public static Employee getEmployee(){
        SystemAdminAuthorizingRealm.Principal principal = getPrincipal();
        if (principal!=null){
           Employee employee = get(principal.getId());
            if (employee != null){
                return employee;
            }
            return new Employee();
        }
        // 如果没有登录，则返回实例化空的User对象。
        return new Employee();
    }

}
